package api

import (
	"api-gateway/pkg"
	"github.com/gin-gonic/gin"
	"net/http"
	"path/filepath"
)

func Upload(c *gin.Context) {
	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": err.Error(),
		})
		return
	}

	if file.Size > 200*1024 { // 2MB
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "文件过大",
		})
		return
	}

	ext := filepath.Ext(file.Filename)
	if ext != ".png" {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "文件格式错误",
		})
		return
	}

	upload, err := pkg.Upload(file)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "上传成功",
		"upload":  upload,
	})
}
